<?php

namespace app\common\model;

use app\common\model\scroll\Notify;
use think\Db;
use think\Model;
use think\Request;

/**
 * 会员模型
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
        'create_text'
    ];

    /**
     * 变更会员余额
     * @param int $money 余额
     * @param int $user_id 会员ID
     * @param string $memo 备注
     * @param int $type
     */
    public static function money($money, $user_id, $memo, $type = 0)
    {
//        Db::startTrans();
//        try {
        $user = self::lock(true)->find($user_id);
        if ($user && $money != 0) {
            $before = $user->money;
            //$after = $user->money + $money;
            $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
            //更新会员信息
            $user->save(['money' => $after]);
            //写入日志
            MoneyLog::create([
                'user_id' => $user_id, 'money' => $money,
                'before' => $before, 'after' => $after,
                'memo' => $memo, 'type' => $type
            ]);
        }
//            Db::commit();
//        } catch (\Exception $e) {
//            Db::rollback();
//        }
    }

    /**
     * 变更会员积分
     * @param int $score 积分
     * @param int $user_id 会员ID
     * @param string $memo 备注
     */
    public static function score($score, $user_id, $memo, $type = 0)
    {
//        Db::startTrans();
//        try {
        $user = self::lock(true)->find($user_id);
        if ($user && $score != 0) {
            $before = $user->score;
            $after = $user->score + $score;
//                $level = self::nextlevel($after);
            //更新会员信息
            $user->save(['score' => $after]);
            //写入日志
            ScoreLog::create([
                'user_id' => $user_id, 'score' => $score,
                'before' => $before, 'after' => $after,
                'memo' => $memo, 'type' => $type
            ]);
        }
//            Db::commit();
//        } catch (\Exception $e) {
//            Db::rollback();
//        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(
            1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000,
            6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000
        );
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }

    public static function parent_col($user_id, $user_ids = [], $level = 2, $now_level = 0)
    {
        if ($now_level >= $level) {
            return $user_ids;
        } else {
            $user_col = self::where("parent_id", "in", $user_id)->where(["status" => "normal"])->column('id');
            if (!$user_col) {
                return $user_ids;
            } else {
                $user_ids = array_merge($user_col, $user_ids);
                return self::parent_col($user_col, $user_ids, $level, $now_level + 1);
            }
        }

    }

    public static function intersection($data, $user, $memo, $type)
    {
        switch ($data['award_type']) {
            case 1:
                $model = new MoneyLog();
                $key = 'money';
                $type_name = "银币";
                break;
            case 2:
                $model = new GoldLog();
                $key = 'gold';
                $type_name = "金币";
                break;
            case 3:
                $model = new ScoreLog();
                $key = 'score';
                $type_name = "积分";
                break;
            case 4:
                $model = new DiamondLog();
                $key = 'diamond';
                $type_name = "钻石";
                break;
            default:
                $type_name = false;
        }
        $before = $user[$key];
        $after = function_exists('bcadd') ? bcadd($user[$key], $data['amount'], 2) : $user[$key] + $data['amount'];
        $model->insertGetId([
            'user_id' => $user['id'], $key => $data['amount'],
            'before' => $before, 'after' => $after,
            'memo' => $memo, 'type' => $type,
            'createtime' => time()
        ]);
//        Notify::log();
        return $type_name;
    }

    public function getCreateTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['createtime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    /**
     * 获取个人URL
     * @param string $value
     * @param array $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }

    /**
     * 获取头像
     * @param string $value
     * @param array $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
//            $rs = Request::instance();
//            $url = $rs->domain();
            $value = '/assets/img/avatar.png';
//            $value = letter_avatar($data['nickname']);
        }
        return $value;
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    public function getCardNumAttr($value, $data)
    {
        if (empty($value)) {
            return $value;
        } else {
            return func_substr_replace($value, '*', 3, 9);
        }
    }
}
